const { series, watch, src, dest } = require('gulp')
const { output, themeRely } = require('./options')
const { theme, page } = require('minimist')(process.argv.slice(2)); // 运行命令传递 theme 名称
const inject = require('gulp-inject')
const connect = require('gulp-connect')

console.log(page);


// 处理 html
const html = () => {
    return src('temp/*')
        .pipe(dest(`${output}/temp`))
}

// 处理 assets
const assets = () => {
    return src('assets/**/*')
        .pipe(dest(`${output}/assets`))
        .pipe(connect.reload())
}

// 处理 index js
const index = () => {
    return src('index.js')
        .pipe(dest(`${output}`))
        .pipe(connect.reload())
}

// 处理 theme 文件夹
const copyThemefiles = () => {
    return src('theme/**/*')
        .pipe(dest(`${output}/theme`))
        .pipe(connect.reload())
}

// inject index
const injectHTML = () => {
    const commonRely = [
        `theme/${theme}/${theme}.js`,
        `theme/${theme}/${theme}.css`,
        `assets/**/*.js`,
        `assets/**/*.css`,
        `index.js`,
    ]

    const res = src(`${output}/temp/${page}.html`)
        .pipe(inject(src([...commonRely, ...(themeRely[theme])], { read: false })))
        .pipe(dest(`${output}/temp`))
        .pipe(connect.reload())

    return res
}

// 开启本地服务
const server = () => {
    connect.server({
        root: 'package',
        port: 9000,
        livereload: true
    })
}

// 监听
const watchChange = () => {
    watch('temp/*.html', series(html, injectHTML));
    watch('theme/**/*.css', series(copyThemefiles, injectHTML))
}

module.exports = {
    html,
    assets,
    copyThemefiles,
    index,
    injectHTML,
    server,
    watchChange,
}
